﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Data;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraGrid.Views.Grid;
using QuanLyKho.DKChung;

namespace QuanLyKho.PhongThanhPham
{
    public partial class Chiasanpham : Form
    {
        public static string MaID = "0";
        public static string IdSanPham = "0";
        public static bool xem = false;
        public string MaSanPham = "";

        public Chiasanpham()
        {
            InitializeComponent();
            Loaddata();
            SetPropertiesGrid();
            SetPropertiesColumns();
        }

        public void Loaddata()
        {
            if (MaID == "0")
            {
                LoadGrid();
                txtChungtu.Text = "SP" + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour
                    + DateTime.Now.Minute + DateTime.Now.Second;
            }
            else
            {
                var data = DataAll.SelectAll("PhieuChiaHang", "*", " WHERE ID=" + MaID);
                dtNgayChia.Value = Convert.ToDateTime(data.Rows[0]["NgayChia"]);
                luNguoiChia.EditValue = data.Rows[0]["NguoiChia"].ToString();
                dtNgayChungTu.Value = Convert.ToDateTime(data.Rows[0]["NgayChungTu"]);
                dtNgayHachToan.Value = Convert.ToDateTime(data.Rows[0]["NgayHoachToan"]);
                txtChungtu.Text = data.Rows[0]["SoChungTu"].ToString();
                txtGhiChu.Text = data.Rows[0]["GhiChu"].ToString();
                var data2 = DataAll.SelectAll("SanPhamHoanThien", "*, IdSanPham AS'MaSanPham', DuoiHang AS'DuoiSP'", " WHERE IDPhieu = " + MaID);
                data2.Rows.Add();
                gridChiaSP.DataSource = null;
                gridChiaSP.DataSource = data2;
                gvChiaSP.OptionsBehavior.Editable = false;
            }
        }

        public void SetPropertiesGrid()
        {
            gvChiaSP.OptionsView.ShowGroupPanel = false;
            //gvChiaSP.OptionsBehavior.Editable = false;
            gvChiaSP.OptionsView.NewItemRowPosition = NewItemRowPosition.None;
            gvChiaSP.OptionsView.ShowFooter = true;
            gcSoLuong.Summary.Add(DevExpress.Data.SummaryItemType.Sum, "SoLuong", "{0:0,0}");
            gcSize.Summary.Add(DevExpress.Data.SummaryItemType.Sum, "Size", "{0:0,0}");
            for (int i = 0; i < gvChiaSP.Columns.Count; i++)
            {
                gvChiaSP.Columns[i].OptionsColumn.AllowSort = DefaultBoolean.False;
            }
        }

        public void SetPropertiesColumns()
        {
            gcXoa.Width = 20;
            gcXoa.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;

            var data = DataAll.SelectAll("DkChung_NhanVien", "MaNhanVien,TenNhanVien", "");
            luNguoiChia.Properties.DataSource = data;
            luNguoiChia.Properties.Columns.Add(new LookUpColumnInfo("MaNhanVien"));
            luNguoiChia.Properties.Columns.Add(new LookUpColumnInfo("TenNhanVien"));
            luNguoiChia.Properties.DisplayMember = "TenNhanVien";
            luNguoiChia.Properties.ValueMember = "MaNhanVien";
            luNguoiChia.Properties.Columns["MaNhanVien"].Visible = false;
            luNguoiChia.Properties.NullText = string.Empty;
            luNguoiChia.Properties.TextEditStyle = TextEditStyles.Standard;
            //luNguoiChia.Properties.SearchMode = SearchMode.AutoComplete;
            luNguoiChia.Properties.ShowHeader = false;

            luMaHang.DataSource = DataAll.SelectAll("PhongMau_SanPham", "MaHang,IdSanPham", "WHERE TrangThai = " + Convert.ToInt32(TrangThai.PhongMau_ThanhPham));
            luMaHang.Columns.Add(new LookUpColumnInfo("MaHang"));
            luMaHang.Columns.Add(new LookUpColumnInfo("IdSanPham"));
            luMaHang.DisplayMember = "MaHang";
            luMaHang.ValueMember = "IdSanPham";
            luMaHang.Columns["IdSanPham"].Visible = false;
            luMaHang.NullText = string.Empty;
            luMaHang.TextEditStyle = TextEditStyles.Standard;
            luMaHang.ShowHeader = false;

            luDuoiSP.DataSource = DataAll.SelectAll("DkChung_Size", "TenSize", "WHERE Loai=N'Đuôi sản phẩm'");
            luDuoiSP.Columns.Add(new LookUpColumnInfo("TenSize"));
            luDuoiSP.DisplayMember = "TenSize";
            luDuoiSP.ValueMember = "TenSize";
            luDuoiSP.NullText = string.Empty;
            luDuoiSP.TextEditStyle = TextEditStyles.Standard;
            luDuoiSP.ShowHeader = false;

            luSize.DataSource = DataAll.SelectAll("DkChung_Size", "TenSize", "WHERE Loai=N'Size bình thường'");
            luSize.Columns.Add(new LookUpColumnInfo("TenSize"));
            luSize.DisplayMember = "TenSize";
            luSize.ValueMember = "TenSize";
            luSize.NullText = string.Empty;
            luSize.TextEditStyle = TextEditStyles.Standard;
            luSize.ShowHeader = false;

            gcSize.OptionsColumn.AllowEdit = false;

            gcSoLuong.DisplayFormat.FormatType = FormatType.Numeric;
            gcSoLuong.DisplayFormat.FormatString = "{0:0,0}";
        }

        public void LoadGrid()
        {
            var dataColumns = new DataTable();
            dataColumns.Columns.Add("MaSanPham");
            dataColumns.Columns.Add("LanSanXuat");
            dataColumns.Columns.Add("DuoiSP");
            dataColumns.Columns.Add("Size");
            dataColumns.Columns.Add("SoLuong", typeof(int));
            dataColumns.Columns.Add("GhiChu");

            pbAnh.Image = null;
            for (int i = 0; i < 1; i++)
            {
                dataColumns.Rows.Add("");
            }
            gridChiaSP.DataSource = null;
            gridChiaSP.DataSource = dataColumns;
        }

        public void LoadImage(string id)
        {
            var MaAnh = DataAll.SelectAll("PhongMau_SanPham", "*", " WHERE IdSanPham=" + id + "");
            var data = DataAll.SelectAll("DkChung_HinhAnh", "*", " WHERE MaAnh=N'" + MaAnh.Rows[0]["MaHang"] + "'");
            if (data.Rows.Count > 0)
            {
                var content = (byte[])data.Rows[0]["Anh"];
                if (content != null)
                {
                    Image newImage;
                    using (var ms = new MemoryStream(content, 0, content.Length))
                    {
                        ms.Write(content, 0, content.Length);
                        newImage = Image.FromStream(ms, true);
                    }
                    pbAnh.Image = newImage;
                }
                else
                {
                    pbAnh.Image = null;
                }
            }
            else
            {
                MessageBox.Show("Không tìm thấy mã ảnh", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public bool Validate1()
        {
            if (luNguoiChia.EditValue == null)
            {
                MessageBox.Show("Bạn phải chọn người chia", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            if (Convert.ToInt32(txtConLai.Text) < 0)
            {
                MessageBox.Show("Số lượng còn không được âm", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            return true;
        }

        public bool CheckSoLuong()
        {
            bool check = true;
            var data = DataAll.SelectAll("PhongMau_SanPham", "*", "WHERE TrangThai = " + Convert.ToInt32(TrangThai.PhongMau_ThanhPham));
            for (int i = 0; i < gvChiaSP.RowCount - 1; i++)
            {
                if (gvChiaSP.RowCount > 1)
                {
                    var datacl = (DataView)gvChiaSP.DataSource;
                    DataRow[] soluongmoi = datacl.Table.Select(" MaSanPham='" + gvChiaSP.GetRowCellValue(i, "MaSanPham") + "'");
                    DataRow[] soluongcu = data.Select(" IdSanPham='" + gvChiaSP.GetRowCellValue(i, "MaSanPham") + "'");
                    int soluong = 0;
                    for (int j = 0; j < soluongmoi.Length; j++)
                    {
                        if (!string.IsNullOrEmpty(soluongmoi[j]["SoLuong"].ToString()))
                        {
                            soluong += Convert.ToInt32(soluongmoi[j]["SoLuong"].ToString());
                        }
                    }
                    if (Convert.ToInt32(soluongcu[0]["SoLuong"].ToString()) - soluong < 0)
                    {
                        MessageBox.Show("Sản phẩm còn lại không được âm", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        check = false;
                        break;
                    }
                    if (cbChiaHet.Checked)
                    {
                        if (Convert.ToInt32(soluongcu[0]["SLConLai"].ToString()) - soluong > 0)
                        {
                            MessageBox.Show("Số lượng sản phẩm cần được chia hết và không âm", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            check = false;
                            break;
                        }
                    }
                }
            }
            return check;
        }

        private void bntLuLai_Click(object sender, EventArgs e)
        {
            if (gvChiaSP.RowCount > 0 && Validate1() && CheckSoLuong())
            {
                if (MaID == "0")
                {
                    var data = DataAll.SelectCustomer("INSERT INTO [dbo].[PhieuChiaHang]([NgayChia],[NguoiChia],[NgayChungTu],[NgayHoachToan]," +
                                                  "[SoChungTu],[GhiChu])VALUES('" + dtNgayChia.Value.ToString("MM/dd/yyyy") + "','" + luNguoiChia.EditValue
                                                  + "','" + dtNgayChungTu.Value.ToString("MM/dd/yyyy") + "','" + dtNgayHachToan.Value.ToString("MM/dd/yyyy") + "','" + txtChungtu.Text
                                                  + "','" + txtGhiChu.Text + "') SELECT MAX(ID) FROM [PhieuChiaHang]");
                    string message = string.Empty;
                    for (int i = 0; i < gvChiaSP.RowCount - 1; i++)
                    {
                        var datasoluong = DataAll.SelectAll("PhongMau_SanPham", "IdSanPham,SLConLai", "");
                        DataRow[] soluongcu = datasoluong.Select(" IdSanPham=" + gvChiaSP.GetRowCellValue(i, "MaSanPham"));
                        var datacl = (DataView)gvChiaSP.DataSource;
                        DataRow[] soluongmoi = datacl.Table.Select(" MaSanPham=" + gvChiaSP.GetRowCellValue(i, "MaSanPham"));
                        int soluong = Convert.ToInt32(soluongcu[0]["SLConLai"].ToString()) - Convert.ToInt32(soluongmoi[0]["SoLuong"].ToString());

                        message = DataAll.Update("PhongMau_SanPham", " [SLConLai] = " + soluong + " WHERE IdSanPham=" + gvChiaSP.GetRowCellValue(i, "MaSanPham"));
                        var datasp = DataAll.SelectAll("PhongMau_SanPham", "*", " WHERE IdSanPham=" + gvChiaSP.GetRowCellValue(i, "MaSanPham"));
                        if (datasp.Rows.Count > 0)
                        {
                            var masosp = DataAll.SelectAll("SanPhamHoanThien", "IdSanPham", " WHERE IdSanPham=" + gvChiaSP.GetRowCellValue(i, "MaSanPham"));
                            if (masosp.Rows.Count <= 0)
                            {
                                message = DataAll.InsertAll("SanPhamHoanThien", data.Rows[0][0] + "," + gvChiaSP.GetRowCellValue(i, "MaSanPham") + "," + datasp.Rows[0]["NhomHang"]
                                    + "," + Convert.ToDateTime(datasp.Rows[0]["NgayThang"].ToString()).ToString("MM/dd/yyyy")
                                    + "," + datasp.Rows[0]["LenhSanXuat"] + "," + Convert.ToDateTime(datasp.Rows[0]["NgayLL"].ToString()).ToString("MM/dd/yyyy")
                                    + "," + datasp.Rows[0]["NguoiDangKy"] + "," + datasp.Rows[0]["NguoiCat"] + "," + datasp.Rows[0]["MaHang"] + "," + gvChiaSP.GetRowCellValue(i, "DuoiSP")
                                    + "," + gvChiaSP.GetRowCellValue(i, "Size") + "," + datasp.Rows[0]["TenHang"] + "," + datasp.Rows[0]["LanSanXuat"] + "," + gvChiaSP.GetRowCellValue(i, "SoLuong")
                                    + "," + datasp.Rows[0]["DonGia"] + "," + datasp.Rows[0]["LoaiHang"] + "," + datasp.Rows[0]["DonVi"] + "," + datasp.Rows[0]["MauSac"] + "," + datasp.Rows[0]["KhoVai"]
                                    + "," + Convert.ToDateTime(datasp.Rows[0]["TuNgay"].ToString()).ToString("MM/dd/yyyy")
                                    + "," + Convert.ToDateTime(datasp.Rows[0]["DenNgay"].ToString()).ToString("MM/dd/yyyy")
                                    + "," + Convert.ToDateTime(datasp.Rows[0]["NgayGCNhan"].ToString()).ToString("MM/dd/yyyy")
                                    + "," + datasp.Rows[0]["GiacSoDo"] + "," + gvChiaSP.GetRowCellValue(i, "GhiChu")
                                    + "," + 0 + "," + datasp.Rows[0]["SoChungTu"]);
                            }
                            else
                            {
                                DataAll.Update("SanPhamHoanThien", " SoLuong=SoLuong+" + gvChiaSP.GetRowCellValue(i, "SoLuong") + " WHERE IdSanPham=" + gvChiaSP.GetRowCellValue(i, "MaSanPham"));
                            }

                        }
                        else
                        {
                            MessageBox.Show("Không tìm thấy sản phẩm", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            DataAll.Delete("PhieuChiaHang", "WHERE ID=" + data.Rows[0][0]);
                            break;
                        }
                    }
                    MessageBox.Show(message.Equals("success") ? "Chia hàng thành công" : message, "Message",
                                            MessageBoxButtons.OK,
                                            message.Equals("success") ? MessageBoxIcon.Information : MessageBoxIcon.Error);
                    Close();
                }
            }
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void gvChiaSP_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.Column.Caption == "Mã sản phẩm")
            {
                if (e.RowHandle == gvChiaSP.RowCount - 1)
                {
                    (gridChiaSP.MainView as GridView).AddNewRow();
                }
                var data = DataAll.SelectAll("PhongMau_SanPham", "*", " WHERE IdSanPham = " + gvChiaSP.GetRowCellValue(e.RowHandle, "MaSanPham") + "");
                txtMaSanPham.Text = gvChiaSP.GetRowCellDisplayText(e.RowHandle, "MaSanPham");
                gvChiaSP.SetRowCellValue(e.RowHandle, "Size", data.Rows[0]["Size"].ToString());
                txtIdSP.Text = gvChiaSP.GetRowCellValue(e.RowHandle, "MaSanPham").ToString();
                txtSoLuong.Text = data.Rows[0]["SLConLai"].ToString();
                txtLoaiHang.Text = data.Rows[0]["LoaiHang"].ToString();
                txtLanTai.Text = data.Rows[0]["LanSanXuat"].ToString();
                txtSoLenh.Text = data.Rows[0]["LenhSanXuat"].ToString();
                dtNgayLL.Value = Convert.ToDateTime(data.Rows[0]["NgayLL"].ToString());
                LoadImage(data.Rows[0]["IdSanPham"].ToString());
                //so luong con lai
                var datacl = (DataView)gvChiaSP.DataSource;
                DataRow[] result = datacl.Table.Select(" MaSanPham='" + gvChiaSP.GetRowCellValue(e.RowHandle, "MaSanPham") + "'");
                int soluong = 0;
                for (int i = 0; i < result.Length; i++)
                {
                    if (!string.IsNullOrEmpty(result[i]["SoLuong"].ToString()))
                    {
                        soluong += Convert.ToInt32(result[i]["SoLuong"].ToString());
                    }
                }
                txtConLai.Text = Convert.ToString(Convert.ToInt32(txtSoLuong.Text) - soluong);
            }
            if (e.Column.Caption == "Số lượng")
            {
                var data = (DataView)gvChiaSP.DataSource;
                DataRow[] result = data.Table.Select(" MaSanPham='" + gvChiaSP.GetRowCellValue(e.RowHandle, "MaSanPham") + "'");
                int soluong = 0;
                for (int i = 0; i < result.Length; i++)
                {
                    soluong += Convert.ToInt32(result[i]["SoLuong"].ToString());
                }
                txtConLai.Text = Convert.ToString(Convert.ToInt32(txtSoLuong.Text) - soluong);
            }
        }

        private void gvChiaSP_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            //txtSoLuong.Text = gcSoLuong.SummaryText;
        }

        private void pbAnh_Click(object sender, EventArgs e)
        {
            var MaAnh = DataAll.SelectAll("PhongMau_SanPham", "MaHang", " WHERE IdSanPham=" + txtIdSP.Text);
            XemAnh.MaID = MaAnh.Rows[0]["MaHang"].ToString();
            var anh = new XemAnh();
            anh.ShowDialog();
            XemAnh.MaID = "0";
        }

        private void gvChiaSP_RowClick(object sender, RowClickEventArgs e)
        {
            if (gvChiaSP.RowCount > 1 && e.RowHandle < gvChiaSP.RowCount - 1)
            {
                var data = DataAll.SelectAll("PhongMau_SanPham", "*", " WHERE IdSanPham = " + gvChiaSP.GetRowCellValue(e.RowHandle, "MaSanPham") + "");
                txtMaSanPham.Text = gvChiaSP.GetRowCellDisplayText(e.RowHandle, "MaSanPham");
                gvChiaSP.SetRowCellValue(e.RowHandle, "Size", data.Rows[0]["Size"].ToString());
                txtIdSP.Text = gvChiaSP.GetRowCellValue(e.RowHandle, "MaSanPham").ToString();
                txtSoLuong.Text = data.Rows[0]["SLConLai"].ToString();
                txtLoaiHang.Text = data.Rows[0]["LoaiHang"].ToString();
                txtLanTai.Text = data.Rows[0]["LanSanXuat"].ToString();
                txtSoLenh.Text = data.Rows[0]["LenhSanXuat"].ToString();
                LoadImage(data.Rows[0]["IdSanPham"].ToString());
                //so luong con lai
                var datacl = (DataView)gvChiaSP.DataSource;
                DataRow[] result = datacl.Table.Select(" MaSanPham='" + gvChiaSP.GetRowCellValue(e.RowHandle, "MaSanPham") + "'");
                int soluong = 0;
                for (int i = 0; i < result.Length; i++)
                {
                    if (!string.IsNullOrEmpty(result[i]["SoLuong"].ToString()))
                    {
                        soluong += Convert.ToInt32(result[i]["SoLuong"].ToString());
                    }
                }
                txtConLai.Text = MaID == "0" ? Convert.ToString(Convert.ToInt32(txtSoLuong.Text) - soluong) : "0";
            }
        }
    }
}
